function writeToTexFile(cellMat,fileName,outputPath,action)
%% writeToTextfile 
%
% function writeToMfile(mat,fileName,outputPath,colNameStru,action,matFieldName,colFieldName)
%
% Given a matrix *mat* write it to a new mfile with name *fileName* in the
% path *outputPath*. The matrix and the names of its columns are writte to the temporary structure 
% tempStru with fieldnames *matFieldName* and *colFieldName*. The names of
% the columns can be provided in the structure *colNameStru*. 
%
%% Required arguments 
%
% *mat:* 2-dimensional matrix. Can be empty. 
%
% *fileName:* name of file  
%
% *outputPath:* where to save file. 
%
%% Optional arguments 
%
% *colNameStru:* cell with the names to give to the columns in structure
% colFieldName
%
% *action:* how to open file. Default is 'w+' which will erase exisiting file. 
%
% *matFieldName:* string with the name to give field in which matrix is saved.
% Default is 'mat'; 
%
% *colFieldName:* string with the name to give field in which matrix is saved.
% Default is 'colName'; 
%
% A. Justiniano January 18 2012 
if nargin < 3 
    error('Need At least 3 input arguments'); 
end 
flagCell=iscell(cellMat); 
if flagCell==false; 
    cellMat=num2cprec(cellMat,7); 
end
if nargin < 4 || isempty(action) 
    action='w+'; 
end 

%% 2. Initialize File 
fileNameM=[fileName,'.txt']; 
cd(outputPath); 
fid=fopen(fileNameM,action); 
if fid==-1 
    disp(['Cannot open ',fileNameM]); 
    disp(['In Directory ',outputPath]); 
end 
cucd=cd; 
[NR NC NP]=size(cellMat); 
if NP > 1 
    error('Matrix cannot have more than 1 Page') 
end 
for jj=1:NR
    for ii=1:NC;        
        temp=char(cellMat{jj,ii});
        tempfind=strfind(temp,'\');
        if isempty(tempfind)==false & tempfind==1
            temp=['\',temp];
        end
        if ii < NC
            fprintf(fid,'%s\t',temp);
            %temp=[temp,'\t'];
        else
            fprintf(fid,'%s\n',temp);            
            %temp=[temp,'\n'];
        end 
    end;
end 

%% 6. Close file 
fclose(fid); 
cd(cucd); 
dispaj('Wrote ',fileNameM,' in ',outputPath); 
